#include "plane.h"

// ========== 初始化与绘制函数 ==========

// 初始化游戏
void Plane::initGame() {
  // 初始化玩家飞机位置（居中底部）
  playerX = (TFT_WIDTH - PLAYER_WIDTH) / 2;
  playerY = PLAYER_START_Y;

  // 初始化子弹数组
  for (int i = 0; i < MAX_BULLETS; i++) {
    bullets[i].active = false;
  }

  // 初始化敌机数组
  for (int i = 0; i < MAX_ENEMIES; i++) {
    enemies[i].active = false;
  }

  // 初始化爆炸效果
  for (int i = 0; i < MAX_ENEMIES; i++) {
    explosions[i].active = false;
  }

  // 初始化游戏数据
  score = 0;
  lives = 3;
  enemiesDestroyed = 0;
  state = PLAYING;

  // 初始化时间
  lastUpdateTime = millis();
  lastFireTime = millis();
  lastEnemySpawnTime = millis();

  // 随机种子
  randomSeed(millis());
}

// 绘制游戏区域边框
void Plane::drawGameArea(Screen& screen) {
  // 绘制顶部边框
  screen.spr.drawLine(0, GAME_TOP, TFT_WIDTH - 1, GAME_TOP, TFT_WHITE);
  // 绘制左右边框
  screen.spr.drawLine(0, GAME_TOP, 0, TFT_HEIGHT - 1, TFT_WHITE);
  screen.spr.drawLine(TFT_WIDTH - 1, GAME_TOP, TFT_WIDTH - 1, TFT_HEIGHT - 1, TFT_WHITE);
}

// 绘制玩家飞机
void Plane::drawPlayer(Screen& screen) {
  int x = (int)playerX;
  int y = (int)playerY;

  // 绘制简单的飞机形状
  // 机身
  screen.spr.fillTriangle(
    x + PLAYER_WIDTH / 2, y,              // 顶部
    x, y + PLAYER_HEIGHT,                 // 左下
    x + PLAYER_WIDTH, y + PLAYER_HEIGHT,  // 右下
    TFT_CYAN);

  // 驾驶舱
  screen.spr.fillCircle(x + PLAYER_WIDTH / 2, y + PLAYER_HEIGHT / 3, 3, TFT_YELLOW);

  // 机翼
  screen.spr.fillRect(x - 4, y + PLAYER_HEIGHT / 2, 4, 6, TFT_CYAN);
  screen.spr.fillRect(x + PLAYER_WIDTH, y + PLAYER_HEIGHT / 2, 4, 6, TFT_CYAN);
}

// 绘制子弹
void Plane::drawBullets(Screen& screen) {
  for (int i = 0; i < MAX_BULLETS; i++) {
    if (bullets[i].active) {
      int x = (int)bullets[i].x;
      int y = (int)bullets[i].y;
      screen.spr.fillRect(x, y, BULLET_WIDTH, BULLET_HEIGHT, TFT_YELLOW);
    }
  }
}

// 绘制敌机
void Plane::drawEnemies(Screen& screen) {
  for (int i = 0; i < MAX_ENEMIES; i++) {
    if (enemies[i].active) {
      int x = (int)enemies[i].x;
      int y = (int)enemies[i].y;
      uint16_t color = getEnemyColor(enemies[i].type);

      // 绘制敌机（倒三角形）
      screen.spr.fillTriangle(
        x, y,                                   // 顶左
        x + ENEMY_WIDTH, y,                     // 顶右
        x + ENEMY_WIDTH / 2, y + ENEMY_HEIGHT,  // 底部
        color);

      // 小细节
      screen.spr.fillCircle(x + ENEMY_WIDTH / 2, y + ENEMY_HEIGHT / 3, 2, TFT_RED);
    }
  }
}

// 绘制爆炸效果
void Plane::drawExplosions(Screen& screen) {
  unsigned long currentTime = millis();

  for (int i = 0; i < MAX_ENEMIES; i++) {
    if (explosions[i].active) {
      unsigned long elapsed = currentTime - explosions[i].startTime;

      if (elapsed < EXPLOSION_DURATION) {
        int frame = (elapsed * EXPLOSION_FRAMES) / EXPLOSION_DURATION;
        int size = 4 + frame * 2;  // 爆炸逐渐变大
        // int alpha = EXPLOSION_FRAMES - frame;  // 逐渐变淡效果（简化版）

        // 绘制多个圆形模拟爆炸
        uint16_t colors[] = { TFT_YELLOW, TFT_ORANGE, TFT_RED };
        for (int j = 0; j < 3; j++) {
          int offset = (j - 1) * 3;
          screen.spr.fillCircle(
            explosions[i].x + offset,
            explosions[i].y + offset,
            size - j,
            colors[j]);
        }
      } else {
        explosions[i].active = false;
      }
    }
  }
}

// 绘制游戏信息
void Plane::drawInfo(Screen& screen) {
  screen.spr.setTextColor(TFT_WHITE, TFT_BLACK);
  screen.spr.setTextDatum(TL_DATUM);

  // 分数
  screen.spr.drawString("分数:", INFO_X, INFO_Y, 2);
  screen.spr.fillRect(INFO_X, INFO_V_Y, 60, 16, TFT_BLACK);
  screen.spr.drawNumber(score, INFO_X, INFO_V_Y, 2);

  // 生命值
  screen.spr.drawString("生命值:", LIVES_X, LIVES_Y, 2);
  screen.spr.fillRect(LIVES_X, LIVES_V_Y, 60, 16, TFT_BLACK);
  screen.spr.drawNumber(lives, LIVES_X, LIVES_V_Y, 2);

  // 击毁敌机数
  screen.spr.drawString("杀敌数:", KILLS_X, KILLS_Y, 1);
  screen.spr.fillRect(KILLS_X, KILLS_V_Y, 60, 16, TFT_BLACK);
  screen.spr.drawNumber(enemiesDestroyed, KILLS_X, KILLS_V_Y, 1);
}

// 绘制暂停提示
void Plane::drawPausedMessage(Screen& screen) {
  screen.spr.fillRect(40, 200, 160, 80, TFT_DARKGREY);
  screen.spr.drawRect(40, 200, 160, 80, TFT_WHITE);
  screen.spr.setTextColor(TFT_YELLOW, TFT_DARKGREY);
  screen.spr.setTextDatum(CC_DATUM);
  screen.spr.drawString("暂停", TFT_WIDTH / 2, 230, 4);
  screen.spr.setTextColor(TFT_WHITE, TFT_DARKGREY);
  screen.spr.drawString("按 A 继续", TFT_WIDTH / 2, 260, 2);
  screen.spr.setTextDatum(TL_DATUM);
}

// 绘制游戏结束界面
void Plane::drawGameOver(Screen& screen) {
  screen.spr.fillRect(30, 180, 180, 120, TFT_RED);
  screen.spr.drawRect(30, 180, 180, 120, TFT_WHITE);
  screen.spr.setTextColor(TFT_WHITE, TFT_RED);
  screen.spr.setTextDatum(CC_DATUM);
  screen.spr.drawString("游戏结束", TFT_WIDTH / 2, 210, 4);
  screen.spr.drawString("分数: " + String(score), TFT_WIDTH / 2, 240, 2);
  screen.spr.drawString("击杀数: " + String(enemiesDestroyed), TFT_WIDTH / 2, 260, 2);
  screen.spr.drawString("B: 重试  X: 退出", TFT_WIDTH / 2, 280, 2);
  screen.spr.setTextDatum(TL_DATUM);
}

// ========== 游戏逻辑函数 ==========

// 移动玩家飞机
void Plane::movePlayer(int dx, int dy) {
  playerX += dx * PLAYER_SPEED;
  playerY += dy * PLAYER_SPEED;

  // 边界检查
  if (playerX < 1) playerX = 1;
  if (playerX > TFT_WIDTH - PLAYER_WIDTH - 1) {
    playerX = TFT_WIDTH - PLAYER_WIDTH - 1;
  }
  if (playerY < GAME_TOP + 1) playerY = GAME_TOP + 1;
  if (playerY > TFT_HEIGHT - PLAYER_HEIGHT - 1) {
    playerY = TFT_HEIGHT - PLAYER_HEIGHT - 1;
  }
}

// 发射子弹
void Plane::fireBullet() {
  unsigned long currentTime = millis();

  // 检查发射间隔
  if (currentTime - lastFireTime < FIRE_INTERVAL) {
    return;
  }

  // 寻找空闲的子弹槽
  for (int i = 0; i < MAX_BULLETS; i++) {
    if (!bullets[i].active) {
      bullets[i].x = playerX + PLAYER_WIDTH / 2 - BULLET_WIDTH / 2;
      bullets[i].y = playerY - BULLET_HEIGHT;
      bullets[i].active = true;
      lastFireTime = currentTime;
      break;
    }
  }
}

// 更新子弹位置
void Plane::updateBullets() {
  for (int i = 0; i < MAX_BULLETS; i++) {
    if (bullets[i].active) {
      bullets[i].y -= BULLET_SPEED;

      // 子弹飞出屏幕，标记为非激活
      if (bullets[i].y < GAME_TOP) {
        bullets[i].active = false;
      }
    }
  }
}

// 生成敌机
void Plane::spawnEnemy() {
  unsigned long currentTime = millis();

  // 检查生成间隔
  if (currentTime - lastEnemySpawnTime < ENEMY_SPAWN_INTERVAL) {
    return;
  }

  // 寻找空闲的敌机槽
  for (int i = 0; i < MAX_ENEMIES; i++) {
    if (!enemies[i].active) {
      enemies[i].x = random(1, TFT_WIDTH - ENEMY_WIDTH - 1);
      enemies[i].y = GAME_TOP + 1;
      enemies[i].type = random(0, 3);  // 随机敌机类型
      enemies[i].active = true;
      lastEnemySpawnTime = currentTime;
      break;
    }
  }
}

// 更新敌机位置
void Plane::updateEnemies() {
  for (int i = 0; i < MAX_ENEMIES; i++) {
    if (enemies[i].active) {
      // 根据类型调整速度
      int speed = ENEMY_SPEED + enemies[i].type;
      enemies[i].y += speed;

      // 敌机飞出屏幕底部
      if (enemies[i].y > TFT_HEIGHT) {
        enemies[i].active = false;
      }
    }
  }
}

// 更新爆炸效果
void Plane::updateExplosions() {
  // 爆炸效果在绘制时自动更新和清理
}

// 检查碰撞
void Plane::checkCollisions() {
  // 检查子弹与敌机的碰撞
  for (int i = 0; i < MAX_BULLETS; i++) {
    if (!bullets[i].active) continue;

    for (int j = 0; j < MAX_ENEMIES; j++) {
      if (!enemies[j].active) continue;

      // 简单的矩形碰撞检测
      if (bullets[i].x + BULLET_WIDTH >= enemies[j].x && bullets[i].x <= enemies[j].x + ENEMY_WIDTH && bullets[i].y <= enemies[j].y + ENEMY_HEIGHT && bullets[i].y + BULLET_HEIGHT >= enemies[j].y) {

        // 击中敌机
        bullets[i].active = false;
        enemies[j].active = false;

        // 增加分数
        score += getEnemyScore(enemies[j].type);
        enemiesDestroyed++;

        // 创建爆炸效果
        createExplosion((int)enemies[j].x + ENEMY_WIDTH / 2,
                        (int)enemies[j].y + ENEMY_HEIGHT / 2);

        break;
      }
    }
  }

  // 检查玩家与敌机的碰撞
  for (int i = 0; i < MAX_ENEMIES; i++) {
    if (!enemies[i].active) continue;

    // 简单的矩形碰撞检测
    if (playerX + PLAYER_WIDTH >= enemies[i].x && playerX <= enemies[i].x + ENEMY_WIDTH && playerY <= enemies[i].y + ENEMY_HEIGHT && playerY + PLAYER_HEIGHT >= enemies[i].y) {

      // 玩家被击中
      enemies[i].active = false;
      lives--;

      // 创建爆炸效果
      createExplosion((int)enemies[i].x + ENEMY_WIDTH / 2,
                      (int)enemies[i].y + ENEMY_HEIGHT / 2);

      // 检查游戏是否结束
      if (lives <= 0) {
        state = GAME_OVER;
      }

      break;
    }
  }
}

// 创建爆炸效果
void Plane::createExplosion(int x, int y) {
  for (int i = 0; i < MAX_ENEMIES; i++) {
    if (!explosions[i].active) {
      explosions[i].x = x;
      explosions[i].y = y;
      explosions[i].startTime = millis();
      explosions[i].active = true;
      break;
    }
  }
}

// 更新游戏状态
void Plane::updateGame() {
  if (state != PLAYING) {
    return;
  }

  updateBullets();
  updateEnemies();
  updateExplosions();
  spawnEnemy();
  checkCollisions();
}

// ========== 输入处理 ==========

void Plane::handleInput(Keys& keys) {
  keys.kvs_update();

  // 暂停/继续
  if (keys.a.pressed()) {
    if (state == PLAYING) {
      state = PAUSED;
    } else if (state == PAUSED) {
      state = PLAYING;
    }
    delay(200);  // 防抖
  }

  // 游戏进行中的控制
  if (state == PLAYING) {
    int dx = 0, dy = 0;

    // 方向键控制移动
    if (!keys.left.read()) {
      dx = -1;
    } else if (!keys.right.read()) {
      dx = 1;
    }

    if (!keys.up.read()) {
      dy = -1;
    } else if (!keys.down.read()) {
      dy = 1;
    }

    if (dx != 0 || dy != 0) {
      movePlayer(dx, dy);
    }

    // O键发射子弹
    if (!keys.o.read()) {
      fireBullet();
    }
  }
}

// ========== 工具函数 ==========

// 获取敌机分数
int Plane::getEnemyScore(int type) {
  switch (type) {
    case 0: return 10;  // 普通敌机
    case 1: return 20;  // 中级敌机
    case 2: return 30;  // 高级敌机
    default: return 10;
  }
}

// 获取敌机颜色
uint16_t Plane::getEnemyColor(int type) {
  switch (type) {
    case 0: return TFT_GREEN;   // 普通敌机
    case 1: return TFT_ORANGE;  // 中级敌机
    case 2: return TFT_RED;     // 高级敌机
    default: return TFT_GREEN;
  }
}

// ========== 主游戏循环 ==========

void Plane::main(Screen& screen, Keys& keys) {
  // 初始化游戏
  initGame();

  // 清屏并设置文本对齐方式
  screen.clearAndLeft();

  // 绘制初始界面
  drawGameArea(screen);
  drawInfo(screen);
  screen.drawScreen();

  // 游戏主循环
  while (true) {
    unsigned long currentTime = millis();

    // 处理输入
    handleInput(keys);

    // 检查是否退出
    if (keys.x.pressed()) {
      screen.clearAndCenter();
      return;
    }

    // 根据游戏状态更新
    if (state == PLAYING) {
      // 更新游戏逻辑（控制帧率）
      if (currentTime - lastUpdateTime > 16) {  // 约60fps
        updateGame();
        lastUpdateTime = currentTime;
      }

      // 重绘游戏画面
      screen.spr.fillRect(1, GAME_TOP + 1, TFT_WIDTH - 2, TFT_HEIGHT - GAME_TOP - 1, TFT_BLACK);
      drawPlayer(screen);
      drawBullets(screen);
      drawEnemies(screen);
      drawExplosions(screen);
      drawInfo(screen);

    } else if (state == PAUSED) {
      // 暂停状态
      drawPausedMessage(screen);

    } else if (state == GAME_OVER) {
      // 游戏结束
      drawGameOver(screen);
      screen.drawScreen();

      // 等待玩家选择
      while (true) {
        keys.kvs_update();

        if (keys.b.pressed()) {
          // 重新开始
          main(screen, keys);
          return;
        }

        if (keys.x.pressed()) {
          // 退出
          screen.clearAndCenter();
          return;
        }

        delay(10);
      }
    }

    // 更新屏幕
    screen.drawScreen();

    delay(10);  // 降低CPU使用率
  }
}
